(function ($) {
    $(document).ready(function () {

        MyDrupal = {};
        MyDrupal.services = {};
        MyDrupal.settings ={};
        MyDrupal.settings.debug = true;
        //MyDrupal.settings.site_path ="";
        //MyDrupal.settings.base_path="nonghua";
        /**
         * Drupal Services XMLHttpRequest Object.
         * @param {Object} options
         */
        MyDrupal.services.call = function(options) {
            try {

                options.debug = false;
                var request = new XMLHttpRequest();
                var url = options.url;

                var method = options.method.toUpperCase();
                // Request Success Handler
                request.onload = function(e) {
                    try {
                        if (request.readyState == 4) {
                            // Build a human readable response title.
                            var title = request.status + ' - ' +
                                http_status_code_title(request.status);
                            // 200 OK
                            if (request.status == 200) {
                                if (MyDrupal.settings.debug) { console.log('200 - OK'); }
                                // Extract the JSON result, or throw an error if the response wasn't
                                // JSON.

                                // Extract the JSON result if the server sent back JSON, otherwise
                                // hand back the response as is.
                                var result = null;
                                var response_header = request.getResponseHeader('Content-Type');
                                if (response_header.indexOf('application/json') != -1) {
                                    result = JSON.parse(request.responseText);
                                }
                                else { result = request.responseText; }

                                options.success(result);

                            }
                            else {
                                // Not OK...
                                if (MyDrupal.settings.debug) {
                                    console.log(method + ': ' + url + ' - ' + title);
                                    console.log(request.responseText);
                                    console.log(request.getAllResponseHeaders());
                                }
                                if (request.responseText) { console.log(request.responseText); }

                                if (typeof options.error !== 'undefined') {
                                    var message = request.responseText || '';
                                    if (!message || message == '') { message = title; }
                                    options.error(request, request.status, message);
                                }

                            }
                        }
                        else {
                            console.log(
                                'Drupal.services.call - request.readyState = ' + request.readyState
                            );
                        }
                    }
                    catch (error) {
                        // Not OK...
                        if (MyDrupal.settings.debug) {
                            console.log(method + ' (ERROR): ' + url + ' - ' + title);
                            console.log(request.responseText);
                            console.log(request.getAllResponseHeaders());
                        }
                        console.log('MyDrupal.services.call - onload - ' + error);
                    }
                };

                // Get the CSRF Token and Make the Request.
                services_get_csrf_token({
                    reset:options.reset,
                    site_path:options.site_path,
                    debug: options.debug,
                    success: function(token) {
                        try {
                            // Async, or sync? By default we'll use async if none is provided.
                            var async = true;
                            if (typeof options.async !== 'undefined' &&
                                options.async === false) { async = false; }

                            // Open the request.
                            request.open(method, url, async);

                            // Determine content type header, if necessary.
                            var contentType = null;
                            if (method == 'POST') {
                                contentType = 'application/json';
                                // The user login resource needs a url encoded data string.
                                if (options.service == 'user' &&
                                    options.resource == 'login') {
                                    contentType = 'application/x-www-form-urlencoded';
                                }
                            }
                            else if (method == 'PUT') {
                                contentType = 'application/json';
                            }

                            // Anyone overriding the content type?
                            if (options.contentType) { contentType = options.contentType; }

                            // Set the content type on the header, if we have one.
                            if (contentType) {
                                request.setRequestHeader('Content-type', contentType);
                            }

                            // Add the token to the header if we have one.
                            if (token) {
                                request.setRequestHeader('X-CSRF-Token', token);
                            }

                            // Send the request with or without data.
                            if (typeof options.data !== 'undefined') {
                                // Print out debug information if debug is enabled. Don't print
                                // out any sensitive debug data containing passwords.
                                if (MyDrupal.settings.debug) {
                                    var show = true;
                                    if (options.service == 'user' &&
                                        in_array(options.resource, ['login', 'create', 'update'])) {
                                        show = false;
                                    }
                                    if (show) {
                                        if (typeof options.data === 'object') {
                                            console.log(JSON.stringify(options.data));
                                        }
                                        else { console.log(options.data); }
                                    }
                                }
                                request.send(JSON.stringify(options.data));
                            }
                            else { request.send(null); }

                        }
                        catch (error) {
                            console.log(
                                'MyDrupal.services.call - services_get_csrf_token - success - ' +
                                error
                            );
                        }
                    },
                    error: function(xhr, status, message) {
                        try {
                            console.log(
                                'MyDrupal.services.call - services_get_csrf_token - ' + message
                            );
                            if (options.error) { options.error(xhr, status, message); }
                        }
                        catch (error) {
                            console.log(
                                'MyDrupal.services.call - services_get_csrf_token - error - ' +
                                error
                            );
                        }
                    }
                });

            }
            catch (error) {
                console.log('MyDrupal.services.call - error - ' + error);
            }
        };


        function services_get_csrf_token(options) {
            try {

                var token;

                // Are we resetting the token?
                if (options.reset) { MyDrupal.sessid = null; }

                // Do we already have a token? If we do, return it the success callback.
                if (MyDrupal.sessid) { token = MyDrupal.sessid; }
                if (token) {
                    if (options.success) { options.success(token); }
                    return;
                }

                // We don't have a token, let's get it from MyDrupal...

                // Build the Request and URL.
                var token_request = new XMLHttpRequest();
                var token_url =options.site_path +
                    '?q=services/session/token';

                // Token Request Success Handler
                token_request.onreadystatechange = function(e) {
                    try {
                        if (token_request.readyState == 4) {
                            var title = token_request.status + ' - ' +
                                http_status_code_title(token_request.status);
                            if (token_request.status != 200) { // Not OK
                                console.log(token_url + ' - ' + title);
                                console.log(token_request.responseText);
                                if (options.error) { options.error(null, token_request.status, "services_get_csrf_token error"); }
                            }
                            else { // OK
                                // Set MyDrupal.sessid with the token, then return the token to the
                                // success function.
                                token = token_request.responseText;
                                MyDrupal.sessid = token;
                                if (options.success) { options.success(token); }
                            }
                        }
                        else {
                            //console.log(
                            //  'services_get_csrf_token - readyState - ' + token_request.readyState
                            //);
                        }
                    }
                    catch (error) {
                        console.log(
                            'services_get_csrf_token - token_request. onload - ' + error
                        );
                    }
                };

                // Open the token request.
                token_request.open('GET', token_url, true);

                // Send the token request.
                token_request.send(null);
            }
            catch (error) { console.log('services_get_csrf_token - ' + error); }
        }
        function http_status_code_title(status) {
            try {
                // @todo - this can be replaced by using the statusText propery on the XHR
                // object.
                //https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Properties
                var title = '';
                switch (status) {
                    case 200: title = 'OK'; break;
                    case 401: title = 'Unauthorized'; break;
                    case 404: title = 'Not Found'; break;
                    case 406: title = 'Not Acceptable'; break;
                    case 500: title = 'Internal Server Error'; break;
                }
                return title;
            }
            catch (error) {
                console.log('http_status_code_title - ' + error);
            }
        }

        var url = window.location.href;
        var reg=new RegExp('portal');
        if(reg.test(url)){
            $('.breadcrumb').hide();
        }
        var reg=new RegExp('app/download');
        if(reg.test(url)){
            $('.breadcrumb').hide();
        }
        var url_forum = window.location.href;
        var reg_forum =new RegExp('forum');
        if(reg_forum.test(url_forum)){
            $('.tabs-wrapper').hide();
        }
        $("#answer-the-question").live('click',function(){
            $('.comment-form').toggle();
            return false;

        })
        $(".address-select-farmer-item").live("click", function () {
            var element_class = $(this).attr('class');
            var class_array = element_class.split(' ');
            var farmer_name = $(this).html();
            if(farmer_name == ""){
                var farmer_name = $('.'+class_array[1]).html();
            }
            $("#address-select-farmer-name-input").val(farmer_name);
            $("#address-select-farmer-id-input").val(class_array[1]);
            $('#farmerModal').modal('hide');

        })
        $("#select-farmer-clear").live("click", function () {

            $("#address-select-farmer-name-input").val('');
            $("#address-select-farmer-id-input").val('');
            $('#farmerModal').modal('hide');

        })



        $(".address-select-distributor-item").live("click", function () {
            var element_class = $(this).attr('class');
            var class_array = element_class.split(' ');
            var farmer_name = $(this).html();
            if(farmer_name == ""){
                var farmer_name = $('.'+class_array[1]).html();
            }
            $("#address-select-distributor-name-input").val(farmer_name);
            $("#address-select-distributor-id-input").val(class_array[1]);
            $('#distributorModal').modal('hide');

        })
        $("#select-distributor-clear").live("click", function () {

            $("#address-select-distributor-name-input").val('');
            $("#address-select-distributor-id-input").val('');
            $('#distributorModal').modal('hide');

        })

        $("#add-fertilizer-info").live("click", function () {
            var id = $("input[name='dif_column_id']").val();
            $("input[name='get_dif_column_id']").val(id);
        })

        //$('#file_upload').on("click",function (event){
        //    //if($('span.file').html() == null){
        //    $(this).find("input[type='file']").click();
        //    //}
        //})

        function _update_countdown(count){
            return function(){
                if((count--)<=0){
                    $('#farmer-register-get-sms-code').attr("disabled",false);
                    $('#farmer-register-get-sms-code').attr("onclick","window.sms_onclick_function()");
                    $('#farmer-register-get-sms-msg').html('');
                    return;
                }
                var str = count + "秒后点击重新发送";
                $('#farmer-register-get-sms-msg').html(str);
                setTimeout(_update_countdown(count),1000);
            }
        }
        window.sms_onclick_function =function () {
            var rule = /^((13[0-9])|147|(15[0-35-9])|173|175|17[0-16-8]|180|182|(18[5-9]))[0-9]{8}$/;
            var cell_num = $("#form-sms-cell").val();
            var graph_code = $("#form-graph-code").val();

            if(window.location.host == 'www.metercomm.com.cn' || window.location.host == 'localhost'){
                var url =  '/nonghua/api/sms?parameters[sms_cell]='+cell_num+'&parameters[graph_code]='+graph_code;
            }else{
                var url =  '/api/sms?parameters[sms_cell]='+cell_num+'&parameters[graph_code]='+graph_code;
            }

            if (!rule.test(cell_num)) {
                alert('请填写正确的手机号码！');
                return false;
            }
            $.ajax({
                url: url,
                //data: {'sms_cell': cell_num},
                type: 'get',
                datatype: 'json',
                success: function (e) {
                    var data = e;
                    if (!data.success) {
                        $('#farmer-register-get-sms-code').attr("disabled",true);
                        $('#farmer-register-get-sms-code').attr("onclick",'');
                        $('#farmer-register-get-sms-code').html("重新发送");
                        setTimeout(_update_countdown(60),1000);
                        //alert('短信已发送！');
                    } else {
                        alert(data.errorNum);
                    }
                    refresh_graph_code_function();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert('textStatus:' + textStatus + XMLHttpRequest.status + errorThrown);
                },

            });
        };
        window.refresh_graph_code_function = function() {
            if(window.location.host == 'metercomm.com.cn' || window.location.host == 'localhost'){
                var url =  '/nonghua/refreshGraph?' + Math.random();
            }else{
                var url =  '/refreshGraph?' + Math.random();
            }

            $("#graph_char").attr("src",url);
        };
        refresh_graph_code_function();

        $("#deteleMore").click(function () {
            var ids = new Array();
            $("input:checked").each(function () {
                ids.push($(this).val());
            });
            if (ids.length == 0) {
                alert('没有选中要删除的信息');
                return false;
            }
            if (window.confirm("确定要删除？")) {
                $.ajax({
                    url: "/farmer/zzxx/del",
                    data: {'ids': ids},
                    type: 'post',
                    //datatype:'json',
                    success: function (e) {
                        // alert(e);return false;
                        //   if(result == 0){
                        //      alert('删除信息成功');
                        location.href = window.location.pathname + "?destion=zzxx";
                        // }
                    }
                });
            }
        })

        $("a.lookUp").click(function () {
            var id = $(this).attr('href');
            $(id).fadeIn('slow');
        })

        $("button.md-close").click(function () {
            $(this).parent().parent().parent().fadeOut("slow");
            $(this).parent().parent().parent().removeClass('in');
            $(".modal-backdrop").remove();
            $("body").removeClass('modal-open');
            $("body").attr("style", "");
        })

        $(document).on("click", "#listViewTableSelectAll",function () {
            $(":checkbox.listViewTableCheck").each(function () {
                $(this).attr("checked", !$(this).attr("checked"));
            });
        })

        $(document).on("click",'#listViewTableDeleteSelected', function () {

            var url = window.location.pathname + '/delete';
            var ids = new Array();
            $("input:checked").each(function () {
                ids.push($(this).val());

            });
            if (ids.length == 0) {
                alert('没有选中要删除的信息');
                return false;
            }
            if (window.confirm("确定要删除选中的信息吗？")) {
                $.ajax({
                    url: url,
                    data: {'ids': ids},
                    type: 'post',
                    datatype: 'json',
                    success: function (e) {
                        var data = eval("(" + e + ")");
                        if (!data.success) {
                            alert('删除信息成功');
                            $('[id^="ajax_pager_wrapper"] [name="search_button"]').click();
                        } else {
                            alert('无权限删除他人数据！')
                        }
                        //location.href = window.location.pathname;
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert('textStatus:'+textStatus+XMLHttpRequest.status+errorThrown);
                    },

                });
            }
        })
        $("#distributor_assign_salesman").live("click", function () {
            var url = window.location.pathname + '/assign';
            var ids = new Array();
            var salesman_id = '';
            $("input:checked").each(function () {
                ids.push($(this).val());

            });
            salesman_id = $("[name$='salesman']").val();
            if (salesman_id == '') {
                alert('没有选择销售员');
                return false;
            }

            if (ids.length == 0) {
                alert('没有选中要分配的经销商');
                return false;
            }
            if (window.confirm("确定要为选中的经销商分配销售员吗？")) {
                $.ajax({
                    url: url,
                    data: {'ids': ids, 'salesman_id': salesman_id},
                    type: 'post',
                    datatype: 'json',
                    success: function (e) {
                        var data = eval("(" + e + ")");
                        if (!data.success) {
                            alert('分配成功');
                            $('[id^="ajax_pager_wrapper"] [name="search_button"]').click();
                        } else {
                            alert('分配失败，请检查是否重复分配！')
                        }
                        //location.href = window.location.pathname;
                    }

                });
            }
        })
        function userUpgradeCancel(role){
            if(window.location.host == 'www.metercomm.com.cn'){
                var url =  '/nonghua/api/upgrade/cancel';
            }else{
                var url =  '/api/upgrade/cancel';
            }
            var ids = new Array();
            $("input:checked").each(function () {
                ids.push($(this).val());
            });
            if (ids.length == 0) {
                alert('没有选中用户');
                return false;
            }

            if (window.confirm("确定要为选中的用户拒绝升级吗？")) {
                if(typeof(window.get_user_token) == "undefined" || window.get_user_token==''){
                    $.ajax({
                        url:window.location.host == 'www.metercomm.com.cn'?"/nonghua/services/session/token":"/services/session/token",
                        type:"get",
                        dataType:"text",
                        async: false,
                        error:function (jqXHR, textStatus, errorThrown) {
                            alert(errorThrown);
                        },
                        success: function (token) {
                            window.get_user_token = token;
                            $.ajaxSetup({
                                beforeSend: function (request) {
                                    request.setRequestHeader("X-CSRF-Token", token);
                                },
                            });
                        }
                    });
                }

                $.ajax({
                    url: url,
                    data: {'ids': ids,'role':role},
                    type: 'post',
                    datatype: 'json',
                    success: function (data) {
                        if (data.success) {
                            alert('操作成功');
                            $('[id^="ajax_pager_wrapper"] [name="search_button"]').click();
                        } else {
                            alert('操作失败！')
                        }
                    }
                });
            }
        }
        function userUpgradeAgree(role){
            if(window.location.host == 'www.metercomm.com.cn'){
                var url =  '/nonghua/api/upgrade/agree';
            }else{
                var url =  '/api/upgrade/agree';
            }
            var ids = new Array();
            $("input:checked").each(function () {
                ids.push($(this).val());
            });
            if (ids.length == 0) {
                alert('没有选中要升级的用户');
                return false;
            }

            if (window.confirm("确定要为选中的用户升级吗？")) {
                if(typeof(window.get_user_token) == "undefined" || window.get_user_token==''){
                    $.ajax({
                        url:window.location.host == 'www.metercomm.com.cn'?"/nonghua/services/session/token":"/services/session/token",
                        type:"get",
                        dataType:"text",
                        async: false,
                        error:function (jqXHR, textStatus, errorThrown) {
                            alert(errorThrown);
                        },
                        success: function (token) {
                            window.get_user_token = token;
                            $.ajaxSetup({
                                beforeSend: function (request) {
                                    request.setRequestHeader("X-CSRF-Token", token);
                                },
                            });
                        }
                    });
                }

                $.ajax({
                    url: url,
                    data: {'ids': ids,'role':role},
                    type: 'post',
                    datatype: 'json',
                    success: function (data) {
                        if (data.success) {
                            alert('升级成功');
                            $('[id^="ajax_pager_wrapper"] [name="search_button"]').click();
                        } else {
                            alert('升级失败！')
                        }
                    }
                });
            }
        }
        $("#farmerUpgradeAgree").on("click", function () {
            userUpgradeAgree("farmer");
        })
        $("#farmerUpgradeCancel").on("click", function () {
            userUpgradeCancel("farmer");
        })

        $("#distributorUpgradeAgree").on("click", function () {
            userUpgradeAgree("distributor");
        })
        $("#distributorUpgradeCancel").on("click", function () {
            userUpgradeCancel("distributor");
        })

        $("input[name='nextButton']").click(function () {
            $("fieldset[class='collapsible form-wrapper collapse-processed']").addClass('collapsed');
            $(this).parent().parent().next().removeClass('collapsed');
        })

        $("input[name='prevButton']").click(function () {
            $("fieldset[class='collapsible form-wrapper collapse-processed']").addClass('collapsed');
            $(this).parent().parent().prev().removeClass('collapsed');
        })

        $('span#span_province').toggle(
            function(){$('span#span_province').html("︿"); $('.add_province').slideDown();},
            function(){$('span#span_province').html("﹀"); $('.add_province').slideUp();}
        )
        $('span#span_city').toggle(
            function(){$('span#span_city').html("︿"); $('.add_city').slideDown();},
            function(){$('span#span_city').html("﹀"); $('.add_city').slideUp();}
        )
        $('span#span_county').toggle(
            function(){$('span#span_county').html("︿"); $('.add_county').slideDown();},
            function(){$('span#span_county').html("﹀"); $('.add_county').slideUp();}
        )
        $('span#span_town').toggle(
            function(){$('span#span_town').html("︿"); $('.add_town').slideDown();},
            function(){$('span#span_town').html("﹀"); $('.add_town').slideUp();}
        )
        $('span#span_village').toggle(
            function(){$('span#span_village').html("︿"); $('.add_village').slideDown();},
            function(){$('span#span_village').html("﹀"); $('.add_village').slideUp();}
        )

        // 取得消息提醒
        if ($('#message_alert').length > 0) {
            $.getJSON(Drupal.settings.basePath + 'api/message_alert', function (json) {
                if (json.new_message) {
                    $('#message_alert').attr("style", "display:none");
                    $('#message_alert_new').removeAttr("style");
                } else {
                    $('#message_alert').removeAttr("style");
                    $('#message_alert_new').attr("style", "display:none");
                }
            });
        }

        //jQuery('.tab-li').on('click',function(){
        //    jQuery('div.'+jQuery('.on').attr('class').substring(0,9)).css('display','none')
        //    jQuery('div.'+jQuery(this).attr('class').substring(0,9)).css('display','block')
        //    jQuery('.on').removeClass('on')
        //    jQuery('li.newprd-s7').remove();
        //    jQuery('.newprd-s7').find('iframe').attr('src','');
        //    jQuery(this).addClass('on')
        //})


        jQuery('.datacount').click(function(){
            var  all_datacount= jQuery(this).parents().parents().parents().attr('class');
            var  datecount= jQuery(this).attr('class');
            var  all_datacountarray= all_datacount.split(" ");
            var  datacountarray= datecount.split(" ");
            var  sumdata = all_datacountarray[2];
            var  need_data = datacountarray[1];
            var new_height ="";
            if( all_datacountarray[1] == 'plant-info-div'){
                switch (need_data){
                    case '20':
                        new_height = '2265px';
                        if(sumdata > 16 && sumdata <19 ){
                            new_height = '2050px';
                        }
                        if(sumdata > 16){
                            break;
                        }
                    case '16':
                        new_height = '1810px';
                        if(sumdata > 12 && sumdata < 15 ){
                            new_height = '1585px';
                        }
                        if(sumdata > 12){
                            break;
                        }
                    case '12':
                        new_height = '1365px';
                        if(sumdata > 8 && sumdata < 11 ){
                            new_height = '1150px';
                        }
                        if(sumdata > 8){
                            break;
                        }
                    case '8':
                        new_height = '920px';
                        if(sumdata > 4 && sumdata < 7 ){
                            new_height = '728px';
                        }
                        if(sumdata > 4){
                            break;
                        }
                    case '4':
                        new_height = '485px';break;
                }
                jQuery(this).parents().parents().parents().find('.plant-info-div').height(new_height);
            }
            if(all_datacountarray[1] == 'soil-info-div'){
                switch (need_data){
                    case '20':
                        new_height = '2700px';
                        if(sumdata > 16 && sumdata <19 ){
                            new_height = '2450px';
                        }
                        if(sumdata > 16){
                            break;
                        }
                    case '16':
                        new_height = '2160px';
                        if(sumdata > 12 && sumdata < 15 ){
                            new_height = '1925px';
                        }
                        if(sumdata > 12){
                            break;
                        }
                    case '12':
                        new_height = '1635px';
                        if(sumdata > 8 && sumdata < 11 ){
                            new_height = '1370px';
                        }
                        if(sumdata > 8){
                            break;
                        }
                    case '8':
                        new_height = '1100px';
                        if(sumdata > 4 && sumdata < 7 ){
                            new_height = '863px';
                        }
                        if(sumdata > 4){
                            break;
                        }
                    case '4':
                        new_height = '575px';break;
                }
                jQuery(this).parents().parents().parents().find('.soil-info-div').height(new_height);
            }
            if(all_datacountarray[1] == 'gift-info-div'){
                switch (need_data){
                    case '20':
                        new_height = '940px';
                        if(sumdata > 16 && sumdata <19 ){
                            new_height = '860px';
                        }
                        if(sumdata > 16){
                            break;
                        }
                    case '16':
                        new_height = '755px';
                        if(sumdata > 12 && sumdata < 15 ){
                            new_height = '680px';
                        }
                        if(sumdata > 12){
                            break;
                        }
                    case '12':
                        new_height = '580px';
                        if(sumdata > 8 && sumdata < 11 ){
                            new_height = '500px';
                        }
                        if(sumdata > 8){
                            break;
                        }
                    case '8':
                        new_height = '400px';
                        if(sumdata > 4 && sumdata < 7 ){
                            new_height = '300px';
                        }
                        if(sumdata > 4){
                            break;
                        }
                    case '4':
                        new_height = '210px';break;
                }
                jQuery(this).parents().parents().parents().find('.gift-info-div').height(new_height);
            }
            if(all_datacountarray[1] == 'fertilizer-info-div'){
                switch (need_data){
                    case '20':
                        new_height = '1130px';
                        if(sumdata > 16 && sumdata <19 ){
                            new_height = '1020px';
                        }
                        if(sumdata > 16){
                            break;
                        }
                    case '16':
                        new_height = '910px';
                        if(sumdata > 12 && sumdata < 15 ){
                            new_height = '790px';
                        }
                        if(sumdata > 12){
                            break;
                        }
                    case '12':
                        new_height = '690px';
                        if(sumdata > 8 && sumdata < 11 ){
                            new_height = '570px';
                        }
                        if(sumdata > 8){
                            break;
                        }
                    case '8':
                        new_height = '470px';
                        if(sumdata > 4 && sumdata < 7 ){
                            new_height = '300px';
                        }
                        if(sumdata > 4){
                            break;
                        }
                    case '4':
                        new_height = '260px';break;
                }
                jQuery(this).parents().parents().parents().find('.fertilizer-info-div').height(new_height);
            }
            if(all_datacountarray[1] == 'revisit-info-div'){
                switch (need_data){
                    case '20':
                        new_height = '1160px';
                        if(sumdata > 16 && sumdata <19 ){
                            new_height = '1030px';
                        }
                        if(sumdata > 16){
                            break;
                        }
                    case '16':
                        new_height = '930px';
                        if(sumdata > 12 && sumdata < 15 ){
                            new_height = '820px';
                        }
                        if(sumdata > 12){
                            break;
                        }
                    case '12':
                        new_height = '710px';
                        if(sumdata > 8 && sumdata < 11 ){
                            new_height = '600px';
                        }
                        if(sumdata > 8){
                            break;
                        }
                    case '8':
                        new_height = '490px';
                        if(sumdata > 4 && sumdata < 7 ){
                            new_height = '380px';
                        }
                        if(sumdata > 4){
                            break;
                        }
                    case '4':
                        new_height = '265px';break;
                }
                jQuery(this).parents().parents().parents().find('.revisit-info-div').height(new_height);
            }
            if(all_datacountarray[1] == 'measure-info-div'){
                switch (need_data){
                    case '20':
                        new_height = '710px';
                        if(sumdata > 16 && sumdata <19 ){
                            new_height = '650px';
                        }
                        if(sumdata > 16){
                            break;
                        }
                    case '16':
                        new_height = '570px';
                        if(sumdata > 12 && sumdata < 15 ){
                            new_height = '510px';
                        }
                        if(sumdata > 12){
                            break;
                        }
                    case '12':
                        new_height = '440px';
                        if(sumdata > 8 && sumdata < 11 ){
                            new_height = '370px';
                        }
                        if(sumdata > 8){
                            break;
                        }
                    case '8':
                        new_height = '310px';
                        if(sumdata > 4 && sumdata < 7 ){
                            new_height = '230px';
                        }
                        if(sumdata > 4){
                            break;
                        }
                    case '4':
                        new_height = '180px';break;
                }
                jQuery(this).parents().parents().parents().find('.measure-info-div').height(new_height);
            }
        })

        // 取得消息提醒
        $('.line1 > a').each(function(index) {
            if ($(this).text() == "我的帐户") {
                var strCookie = document.cookie;
                var arrCookie = strCookie.split("; ");
                for(var i = 0; i < arrCookie.length; i++) {
                    var arr = arrCookie[i].split("=");
                    if('username' == arr[0]) {
                        $(this).text(decodeURI(arr[1]));
                    }
                }
            }
        });

        $('#p,#n,#k').focusout(function(){
            var n = $('#n').val()?$('#n').val():0;
            var p = $('#p').val()?$('#p').val():0;
            var k = $('#k').val()?$('#k').val():0;
            var total = parseFloat(n,2)+parseFloat(p,2)+parseFloat(k,2);
            $('#npk_total').val(total);
        })

//		$('#edit-province').bind('change', function () {
//			var pid = document.getElementById('edit-province').value;
//			alert(pid);
//			$.ajax({
//				type: "get",
//				url: "/retailstore/check",
//				data: {'level': "1", 'pid': pid},
//				dataType: "json",
//				async: false,
//				success: function (data) {
////					var e = data.demo_info
//alert('testing');
//					$.each(data, function (i, e) {
//						var myoption = document.createElement("option");
//						myoption.value = e.id;
//						myoption.innerHTML=e.name
//						document.getElementById('edit-city').appendChild(myoption)
//					})
//				}
//			});
//
//		});

        $(".openORclose").live("click",function(){
            $(".search-div").toggle();
            if($(".search-div").css('display') == 'none'){
                $(".openORclose").html('展开搜索')
            }else if($(".search-div").css('display') == 'block'){
                $(".openORclose").html('关闭搜索')
            }
        })

        $('#ajax_input_farmer_button').click(function(){
            var address_fuzzy = $('input[name="address_fuzzy"]').val();
            var province = $('select[name="province"]').val();
            var city = $('select[name="city"]').val();
            var county = $('select[name="county"]').val();
            var town = $('select[name="town"]').val();
            var village = $('select[name="village"]').val();
            var farmer_name = $('input[name="farmername"]').val();
            var cell = $('input[name="telephone"]').val();
            var gender = $('input[name="input_farmer_gender"]:checked').val();
            var addr_detail = $('input[name="input_farmer_addr_detail"]').val();
            var email = $('input[name="input_farmer_email"]').val();
            var type = $('input[name="input_farmer_type"]').val();
            var farmer_area = $('input[name="input_farmer_farm_area"]').val();
            var soil_type = $('input[name="input_farmer_soil_type"]').val();
            var soil_fertility = $('input[name="input_farmer_soil_fertility"]').val();
            var comments = $('textarea[name="input_farmer_comments"]').val();

            if(window.location.host == 'www.metercomm.com.cn'){
                var url = "/nonghua/drupalgap/mobile_service_resources/farmer_add";
            }else{
                var url = "/drupalgap/mobile_service_resources/farmer_add";
            }
            if(address_fuzzy == ""){
                var addressOption = new Array();
                addressOption['province'] = province;
                addressOption['city'] = city;
                addressOption['county'] = county;
                addressOption['town'] = town;
                addressOption['village'] = village;


                if(province == '' && city == '' && county == ''){
                    alert('请选地址');
                    return;
                }
                if(farmer_name == ''){
                    alert('农户姓名必填');
                    return;
                }
                if( cell == ''){
                    alert('手机号必填');
                    return;
                }
                if (!_js_test_tel(cell)) {
                    alert( '手机号码格式有误!');
                    return;
                }

             var addr_id = _get_address_id(addressOption);
            }
            $('#ajax_input_farmer_button').attr('disabled',true);
            MyDrupal.services.call({
            site_path:window.location.host,
                url: "https://"+window.location.host+url,
                data: {'address_fuzzy':address_fuzzy,'addr_id':addr_id,'farmer_name':farmer_name,'cell':cell,'farmer_id':'','addr_detail':addr_detail,'email':email,'type':type,'farm_area':farmer_area,'soil_type':soil_type,'soil_fertility':soil_fertility,'comments':comments,'gender':gender},
                method: 'post',
                //reset:true,
                datatype: 'json',
                success: function (data) {
                    $('#ajax_input_farmer_button').attr('disabled',false);
                    if(data.option == 1){
                        alert("添加成功");
                    }else{
                        alert(data.error);
                    }

                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $('#ajax_input_farmer_button').attr('disabled',false);
                    alert('textStatus:'+textStatus+XMLHttpRequest.status+errorThrown);
                },
            });
        })

        $('#ajax_input_address_town').click(function(){
            var province = $('select[name="province"]').val();
            var city = $('select[name="city"]').val();
            var county = $('select[name="county"]').val();
            var town = $('select[name="town"]').val();
            var address_fuzzy = $('input[name="address_fuzzy"]').val();
            var address_town = $('input[name="input_address_town"]').val();
            var address_village = "";
            if(county == '' && address_fuzzy == '' ){
                alert('请选择县')
                return false;
            }

            if(address_town == ''){
                alert('请填写地址名称！')
                return false;
            }
            if(window.location.host == 'www.metercomm.com.cn'){
                var path_to_source = "/nonghua/api/address/add";
            }else{
                var path_to_source = "/api/address/add";
            }
            var httpstr = '';
            if(window.location.host == 'www.junong360.com'){
                httpstr = "https://";
            }else{
                httpstr = "http://";
            }
            var params = {
                province:province,
                city:city,
                county:county,
                town:town,
                address_fuzzy:address_fuzzy,
                new_town:address_town,
                new_village:address_village,
            }
            $('#ajax_input_address_town').attr('disabled',true);
            MyDrupal.services.call({
                site_path:window.location.host,
                url: httpstr +window.location.host+path_to_source,
                data: params,
                method: 'post',
                //reset:true,
                datatype: 'json',
                success: function (data) {
                    $('#ajax_input_address_town').attr('disabled',false);
                    if(data.state == 1){
                        alert("添加成功");
                    }else{
                        alert(data.dsc);
                    }

                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $('#ajax_input_address_town').attr('disabled',false);
                    alert('textStatus:'+textStatus+XMLHttpRequest.status+errorThrown);
                },
            });
            //_get_datasouce_result({
            //    path: path_to_source,
            //    param: params,
            //    resource: 'add',
            //    success: function (data) {
            //        alert('成功')
            //    },
            //    error: function (xhr, status, message) {
            //       alert('失败')
            //    }
            //});
        })
        $('input[name="perennial"]').click(function(){
            var value = $('input[name="perennial"]:checked').val();
            if(value == 2){
                $('.perennial_change_title').text('实施日期:');
            }else{
                $('.perennial_change_title').text('播种日期:');
            }
        })
        $('#ajax_input_address_village').click(function(){
            var province = $('select[name="province"]').val();
            var city = $('select[name="city"]').val();
            var county = $('select[name="county"]').val();
            var town = $('select[name="town"]').val();
            var address_fuzzy = $('input[name="address_fuzzy"]').val();
            var address_town = "";
            var address_village = $('input[name="input_address_village"]').val();


            if(town == ''&&address_fuzzy==''){
                alert('请选择镇');
                return false;
            }
            if( address_village == ''){
                alert('请填写地址名称！')
                return false;
            }
            if(window.location.host == 'www.metercomm.com.cn'){
                var path_to_source = "/nonghua/api/address/add";
            }else{
                var path_to_source = "/api/address/add";
            }
            var httpstr = '';
            if(window.location.host == 'www.junong360.com'){
                httpstr = "https://";
            }else{
                httpstr = "http://";
            }
            var params = {
                province:province,
                city:city,
                county:county,
                town:town,
                address_fuzzy:address_fuzzy,
                new_town:address_town,
                new_village:address_village,
            }
            $('#ajax_input_address_village').attr('disabled',true);
            MyDrupal.services.call({
                site_path:window.location.host,
                url: httpstr + window.location.host+path_to_source,
                data: params,
                method: 'post',
                //reset:true,
                datatype: 'json',
                success: function (data) {
                    $('#ajax_input_address_village').attr('disabled',false);
                    if(data.state == 1){
                        alert("添加成功");
                    }else{
                        alert(data.dsc);
                    }

                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $('#ajax_input_address_village').attr('disabled',false);
                    alert('textStatus:'+textStatus+XMLHttpRequest.status+errorThrown);
                },
            });
            //_get_datasouce_result({
            //    path: path_to_source,
            //    param: params,
            //    resource: 'add',
            //    success: function (data) {
            //        alert('成功')
            //    },
            //    error: function (xhr, status, message) {
            //       alert('失败')
            //    }
            //});
        })
    })
})(jQuery);
function _get_address_id(addressOption) {
    var address = '';
    if (addressOption['village']!= "" && addressOption['village'] ) {
        address = addressOption['village'];
    } else if (addressOption['town'] && addressOption['town'] != "") {
        address = addressOption['town'];
    } else if (addressOption['county'] && addressOption['county'] != "" ) {
        address = addressOption['county'];
    } else if (addressOption['city'] && addressOption['city'] != "" ) {
        address = addressOption['city'];
    } else if (addressOption['province'] && addressOption['province'] != "" ) {
        address = addressOption['province'];
    }
    return address ;
}
function _js_test_tel(cell){
    //var rule  = /^((13[0-9])|147|(15[0-35-9])|180|182|(18[5-9]))/;
    var rule = /^((13[0-9])|147|(15[0-35-9])|180|182|(18[5-9]))[0-9]{8}$/;
    return rule.test(cell);
}
function editfriend(type,ID,name,chat_id){
    if(window.location.host == 'www.metercomm.com.cn'){
        var url =  '/nonghua/manage_chat/edit';
    }else{
        var url =  '/manage_chat/edit';
    }
    //alert(url);return false;
    var confrim = '';
    var success = '';
    var error = '';
    var ids = new Array();
    if(type == 'add'){
        confrim = '加为好友？';
        success = '添加好友成功！';
        error = '添加好友失败！';
    }else if(type == 'del'){
        confrim = '删除好友？';
        success = '删除好友成功！';
        error = '删除好友失败！';
    }else{
        confrim = '确认修改分组？';
        success = '修改分组成功！';
        error = '修改分组失败！';

        jQuery("input:checked").each(function () {
            ids.push(jQuery(this).val());
        });
        if (ids.length == 0) {
            alert('没有选中要分配的好友');
            return false;
        }
    }
    if (window.confirm(confrim)) {
        var group_id = jQuery("select[name='chat_group_assign']").val() ? jQuery("select[name='chat_group_assign']").val() : 1;
        jQuery.ajax({
            url: url,
            data: {'type':type,'user_id': ID, 'user_name': name,'chat_id':chat_id,'group_id':group_id,'ids':ids},
            type: 'post',
            datatype: 'json',
            success: function (e) {
                var data = eval("(" + e + ")");
                if (!data.success) {
                    alert(success);
                    if(type == 'add'){
                        jQuery('.'+ID).remove();
                    }else if(type == 'del'){
                        jQuery('.'+chat_id).remove();
                    }
                } else {
                    alert(error)
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert('textStatus:'+textStatus+XMLHttpRequest.status+errorThrown);
            },
        });
    }
}


function update_tab(url){
    jQuery('div.'+jQuery('.on').attr('class').substring(0,9)).css('display','none');
    jQuery('.on').removeClass('on');
    jQuery('.hp-tab-newprd').find('.newprd-s7 iframe').attr('src',url+'/iframe');
    jQuery('div.newprd-s7').show();
    jQuery('.j-sw-nav').append('<li class="newprd-s7 on"><a href="javascript:void(0)">修改</a></li>');
}


function delete_fertilizer(tableName,id){
    if (window.location.host == 'www.metercomm.com.cn') {
        var url = '/nonghua/fertilizer/delete';
    } else {
        var url = '/fertilizer/delete';
    }
    if(window.confirm("确定要删除么？")){
        jQuery.ajax({
            url: url,
            data: {'tableName':tableName,'id':id},
            type: 'post',
            //datatype: 'json',
            success: function (e) {
                if(e){
                    alert('删除成功')
                    var submit_ids = jQuery("input[name='submit_id']").val();
                    if(submit_ids!=""){
                        var submit_arr = submit_ids.split(',');
                        var i = submit_arr.indexOf(id);
                        submit_arr.splice(i,1);
                        jQuery("input[name='submit_id']").val(submit_arr.join(","));
                    }
                    jQuery('.'+id).remove();
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert('textStatus:'+textStatus+XMLHttpRequest.status+errorThrown);
            },
        })
    }
}

function ajax_table_delete_item(url,id){
    if (window.location.host == 'www.metercomm.com.cn') {
        url = '/nonghua'+url;
    }
    var ids = new Array();
    ids.push(id);
    if (window.confirm("确定要删除选中的信息吗？")) {
        jQuery.ajax({
            url: url,
            data: {'ids': ids},
            type: 'post',
            datatype: 'json',
            success: function (e) {
                var data = eval("(" + e + ")");
                if (!data.success) {
                    alert('删除信息成功');
                    jQuery('.fertilization-div.'+id).remove();;
                } else {
                    alert('无权限删除他人数据！')
                }
                //location.href = window.location.pathname;
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert('textStatus:'+textStatus+XMLHttpRequest.status+errorThrown);
            },

        });
    }
}

function assign_chat_room(){
    if (window.location.host == 'www.metercomm.com.cn') {
        var url = '/nonghua/manage_chat/assign_chat_room';
    } else {
        var url = '/manage_chat/assign_chat_room';
    }
    var ids = new Array();
    jQuery("input:checked").each(function () {
        ids.push(jQuery(this).val());
    });
    if (ids.length == 0) {
        alert('没有选中要加入聊天群的好友！');
        return false;
    }
    var chat_room_id = jQuery("select[name='chat_room_assign']").val() ? jQuery("select[name='chat_room_assign']").val() : '';
    if(chat_room_id == ""){
        alert('没有选择聊天群！');
        return false;
    }
    if(window.confirm("确定要加TA进聊天群么？")){
        jQuery.ajax({
            url: url,
            data: {'chat_room_id':chat_room_id,'ids':ids},
            type: 'post',
            datatype: 'json',
            success: function (obj) {
                var data = eval("(" + obj + ")");
                if(data.success){
                    alert('加入聊天群成功！')
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //alert('textStatus:'+textStatus+XMLHttpRequest.status+errorThrown);
				alert('该聊天室已经有他了哦~');
            },
        })
    }
}

function gift_assign(){
    var url = window.location.pathname + '/assign';
    var ids = new Array();
    var gift_type = '';
    var quantity = '';
    var comments = '';
    jQuery("input:checked").each(function () {
        ids.push(jQuery(this).val());

    });
    gift_type = jQuery("[name$='gift_type']").val();
    quantity = jQuery("[name$='quantity']").val();
    comments = jQuery("[name$='comments']").val();
    if (gift_type == '') {
        alert('没有选择礼物类型');
        return false;
    }
    if (quantity == '') {
        alert('没有填写数量');
        return false;
    }

    if (ids.length == 0) {
        alert('没有选中要分配的农户');
        return false;
    }
    if (window.confirm("确定要为选中的农户分配礼物吗？")) {
        jQuery.ajax({
            url: url,
            data: {'ids': ids,'gift_type':gift_type,'quantity':quantity,'comments':comments},
            type: 'post',
            datatype: 'json',
            success: function (e) {
                var data = eval("(" + e + ")");
                if (!data.success) {
                    alert('分配成功');
                    jQuery('[id^="ajax_pager_wrapper"] [name="search_button"]').click();
                } else {
                    alert('分配失败，请检查是否重复分配！')
                }
                //location.href = window.location.pathname;
            }

        });
    }
}

function delete_retailstore(tableName,id){
    if (window.location.host == 'www.metercomm.com.cn') {
        var url = '/nonghua/retailstore_sales/delete';
    } else {
        var url = '/retailstore_sales/delete';
    }
    if(window.confirm("确定要删除么？")){
        jQuery.ajax({
            url: url,
            data: {'tableName':tableName,'id':id},
            type: 'post',
            //datatype: 'json',
            success: function (e) {
                if(e){
                    alert('删除成功')
                    var submit_ids = jQuery("input[name='submit_id']").val();
                    if(submit_ids!=""){
                        var submit_arr = submit_ids.split(',');
                        var i = submit_arr.indexOf(id);
                        submit_arr.splice(i,1);
                        jQuery("input[name='submit_id']").val(submit_arr.join(","));
                    }
                    jQuery('.'+id).remove();
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert('textStatus:'+textStatus+XMLHttpRequest.status+errorThrown);
            },
        })
    }
}